package com.ruipeng.shengyapo.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import com.ruipeng.shengyapo.model.CropImage;
import com.ruipeng.shengyapo.utils.ContentUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;



@Controller
@RequestMapping("imgUploadCtl")
public class ImgUploadController{

	private String IMG_PRJ_PATH = "/image/"; // 文件存放目录
	private String IMG_PRJ_PATH_TMP = "/image/image_tmp/";// 临时文件存放目录
	private String IMG_PRJ_PATH_CROP = "/image/crop/";// 临时剪裁文件存放目录
	private String DIR_TMP = "temp";// 临时文件存放目录
	private int INT_SCALE = 2;
	
	/**
	 *上传图片
	 * @param imageFile
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "imgUpload" , method =RequestMethod.POST)
	public Map<String, Object> imgUpload(@RequestParam(value = "img") MultipartFile imageFile, HttpServletRequest request){
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
			//文件路径
			String filePath = getFilePath(request, IMG_PRJ_PATH_TMP);
			String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			Random random = new Random();
			String fileName = imageFile.getOriginalFilename();
			fileName = String.format("%s_%s", dateStr, random.nextInt(10000))+fileName.substring(fileName.lastIndexOf("."));
			
			File targetFile = new File(filePath, fileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}

			// 保存到服务器物理磁盘
			try {
				imageFile.transferTo(targetFile);
			} catch (Exception e) {
				e.printStackTrace();
			}

			BufferedImage img = ImageIO.read(targetFile);
			// croppic 需要的属性
			map.put("status", "success");
			map.put("url",  basePath+IMG_PRJ_PATH_TMP +fileName);
			map.put("width", img.getWidth());
			map.put("height", img.getHeight());
			System.out.println("imageUrl = " + basePath+IMG_PRJ_PATH_TMP +fileName);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", "error");
			map.put("message", "your error message text");
		}
		return map;
	}
	
	/**
	 *上传图片
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(params="webImgCrop", method=RequestMethod.POST)
	public Map<String, Object> webImgCrop(@RequestParam(value="imgUrl",required=false) String imgUrl,
			@RequestParam(value = "imgW",required=false) double imgW,
			@RequestParam(value = "imgH",required=false) double imgH,
			@RequestParam(value = "imgX1",required=false) Integer imgX1,
			@RequestParam(value = "imgY1",required=false) Integer imgY1,
			@RequestParam(value = "cropW",required=false) Integer cropW,
			@RequestParam(value = "cropH",required=false) Integer cropH,
			HttpServletRequest request) {
		Map<String, Object> map=new HashMap<String, Object>();
		try {
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
			String serviceId = request.getParameter("serviceId");

			String filePath = "user/";
//			if(StringUtils.isNotBlank(serviceId)){
//				if(ContentUtils.IMG_SERVICE_PRODUCT.equals(serviceId)){
//					String productId = request.getParameter("productId");
//					productId = StringUtils.isBlank(productId)? DIR_TMP: productId;
//					filePath = "product/"+ productId +"/";
//				} else if(ContentUtils.IMG_SERVICE_PRIZE.equals(serviceId)){
//					String prizeId = request.getParameter("prize");
//					prizeId = StringUtils.isBlank(prizeId)? DIR_TMP: prizeId;
//					filePath = "prize/"+ prizeId +"/";
//				}
//			}

			CropImage image=new CropImage((int)imgW * INT_SCALE, (int)imgH * INT_SCALE, imgX1 * INT_SCALE, imgY1 *INT_SCALE, cropW * INT_SCALE, cropH * INT_SCALE);
			
			String IMG_URL = "";
			String subpath = "";//要保存的文件本地路径
			String url = "";//照片网络路径
			if(imgUrl.indexOf(IMG_PRJ_PATH_TMP) != -1){ //上传新照片
				IMG_URL = imgUrl.split(IMG_PRJ_PATH_TMP)[1];
				imgUrl = getFilePath(request, IMG_PRJ_PATH_TMP) + IMG_URL;
				subpath = getFilePath(request, IMG_PRJ_PATH_CROP) + IMG_URL;
				url = IMG_PRJ_PATH_CROP + IMG_URL;
			} else if(imgUrl.indexOf(IMG_PRJ_PATH_CROP) != -1){ //修改上传到image/crop下的照片
				url = imgUrl;
				IMG_URL = imgUrl.split(IMG_PRJ_PATH_CROP)[1];
				imgUrl = getFilePath(request, IMG_PRJ_PATH_CROP) + IMG_URL;
				subpath = imgUrl;
			} else { // 修改上传到image/activityId/brideId下的照片
				url = imgUrl;
				IMG_URL = imgUrl.split(IMG_PRJ_PATH)[1];
				imgUrl = getFilePath(request, IMG_PRJ_PATH) + IMG_URL;
				subpath = imgUrl;
				IMG_URL = IMG_URL.indexOf("/"+ DIR_TMP +"/") != -1? IMG_URL.split(DIR_TMP +"/")[1]: IMG_URL.replace(filePath, "");
			}

			subpath = getFilePath(request, IMG_PRJ_PATH) + filePath + IMG_URL;
			url = IMG_PRJ_PATH + filePath + IMG_URL; //照片网络路径
			url = url.replace("//", "/");
			
			image.setSrcPath(imgUrl);
			image.setSubPath(subpath);
			image.cut();
			if(!subpath.equals(imgUrl)){
				this.deleteFile(imgUrl);
			}
			map.put("status", "success");
			map.put("url", basePath + url);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", "error");
			map.put("message", "your error message text");
		}
		return map;
	}
	
	private String getFilePath(HttpServletRequest request,String path){
		// 项目本地根目录
		//req.getSession().getServletContext().getRealPath("/") = "E:\tomcat-out\HunParUpload\webapps\HunParUpload\"
		String filePath = request.getSession().getServletContext().getRealPath("/").replace("\\", "/");
		
		//req.getContextPath() = "/HunParUpload"
		return filePath.substring(0, filePath.lastIndexOf(request.getContextPath()))+ path;
	}

	/**
	 * 删除文件
	 * @param filePath
	 * @return
	 */
	private boolean deleteFile(String filePath){
		if(StringUtils.isEmpty(filePath)){
			return false;
		}
		//删除tmp图片
		File file=new File(filePath);
		if(file.exists()){
			return file.delete();
		}
		return false;
	}
}
